namespace SimpleWebServices.Configuration
{
    using System;
    using System.Collections.ObjectModel;
    using System.Configuration;
    using System.Linq;
    using System.Xml;

    public sealed class SubmissionConfiguration : IConfigurationSectionHandler
    {
        public static void Clear()
        {
            SubmissionConfiguration.Settings().Clear();
        }

        public static SubmissionHandlerSetting Handler(string name)
        {
            if (null == name)
            {
                throw new ArgumentNullException("name");
            }
            else if (0 == name.Length)
            {
                throw new ArgumentOutOfRangeException("name");
            }

            return SubmissionConfiguration.Settings().Where(x => name.Equals(x.Name, StringComparison.Ordinal)).First();
        }

        public static void Reset()
        {
            ConfigurationManager.RefreshSection("simplewebservices/submission");
        }

        public static Collection<SubmissionHandlerSetting> Settings()
        {
            return SubmissionConfiguration.Settings("simplewebservices/submission");
        }

        public static Collection<SubmissionHandlerSetting> Settings(string sectionName)
        {
            Collection<SubmissionHandlerSetting> result = ConfigurationManager.GetSection(sectionName) as Collection<SubmissionHandlerSetting>;

            return result ?? new Collection<SubmissionHandlerSetting>();
        }

        public object Create(object parent, object configContext, XmlNode section)
        {
            Collection<SubmissionHandlerSetting> result = new Collection<SubmissionHandlerSetting>();

            if (section != null)
            {
                try
                {
                    XmlNodeList list = section.SelectNodes("./handler");
                    foreach (XmlNode node in list)
                    {
                        result.Add(node.OuterXml.Deserialize<SubmissionHandlerSetting>());
                    }
                }
                catch (Exception exception)
                {
                    throw new ConfigurationErrorsException(exception.Message, exception, section);
                }
            }

            return result;
        }
    }
}